﻿using System;
using System.IO;
using WaveLib;
//using Yeti.MMedia.Mp3;
using Id3Lib;
using System.Windows.Forms;
//using Yeti.Lame;
using System.Diagnostics;
using Yeti.Lame;


namespace CD2WebAudio3Lib
{
    public delegate void MP3ProgressHandler(object pSender, decimal pPercentDone);

    public class mp3_creator
    {

        //public event MP3ProgressHandler MP3Progress;

        public bool Cancel = false;

        public bool Create_MP3(string pWaveFileName, string pOutputFileName, uint pBitRate, string pAuthor, string pTitle, string pCopyright, int pMilliseconds)
        {
            if (File.Exists(pOutputFileName))
            {
                File.Move(pOutputFileName, pOutputFileName + "." + DateTime.Now.ToString("yyyyMMddhhmmss"));
            }

            //WaveStream inputStream = new WaveStream(pWaveFileName);
            //try
            //{
            //    // initialize configuration
            //    Yeti.Lame.BE_CONFIG cfg = new Yeti.Lame.BE_CONFIG(inputStream.Format);

            //    cfg.format.lhv1.nPreset = Yeti.Lame.LAME_QUALITY_PRESET.LQP_CBR;
            //    cfg.dwConfig = Convert.ToUInt32(256);
            //    cfg.format.lhv1.dwStructVersion = 1;
            //    cfg.format.lhv1.dwStructSize = 331;
            //    cfg.format.lhv1.nMode = Yeti.Lame.MpegMode.JOINT_STEREO;
            //    cfg.format.lhv1.dwSampleRate = Convert.ToUInt32(96000); // Convert.ToUInt32(44100);
            //    cfg.format.lhv1.dwReSampleRate = 0;
            //    cfg.format.lhv1.dwBitrate = Convert.ToUInt32(32); // Convert.ToUInt32(128);
            //    cfg.format.lhv1.dwMpegVersion = Convert.ToUInt32(1); //  Convert.ToUInt32(0);
            //    cfg.format.lhv1.dwPsyModel = Convert.ToUInt32(3);  // Convert.ToUInt32(0);
            //    cfg.format.lhv1.dwEmphasis = Convert.ToUInt32(0);
            //    cfg.format.lhv1.bOriginal = Convert.ToInt32(1);
            //    cfg.format.lhv1.bWriteVBRHeader = Convert.ToInt32(1);
            //    cfg.format.lhv1.bNoRes = Convert.ToInt32(1);

            //    // set bit rate
            //    cfg.format.lhv1.dwBitrate = pBitRate;

            //    Mp3Writer writer = new Mp3Writer(new FileStream(pOutputFileName, FileMode.Create), inputStream.Format, cfg);

            //    try
            //    {
            //        // insert the ID3v2 tags
            //        FrameManager.Serialize(create_ID3v2_Tags(pAuthor, pTitle, pCopyright, pMilliseconds), writer.BaseStream);

            //        byte[] buff = new byte[writer.OptimalBufferSize];
            //        int read = 0;
            //        decimal actual = 0;
            //        decimal total = inputStream.Length;

            //        while ((read = inputStream.Read(buff, 0, buff.Length)) > 0)
            //        {
            //            Application.DoEvents();
            //            writer.Write(buff, 0, read);
            //            actual += read;
            //            MP3Progress(this, (decimal)(actual * 100 / total));
            //            Application.DoEvents();
            //            if (Cancel) return false;
            //        }

            //        return true;

            //    }
            //    finally
            //    {
            //        writer.Close();
            //    }
            //}
            //finally
            //{
            //    inputStream.Close();
            //}

            string fixedWaveName = pWaveFileName;
            if (fixedWaveName.Contains(" ")) fixedWaveName = "\"" + fixedWaveName + "\"";

            string fixedOutName = pOutputFileName;
            if (fixedOutName.Contains(" ")) fixedOutName = "\"" + fixedOutName + "\"";

            string lameEXE = AppPath + "lame.exe";
            string lameArgs = string.Format("-b {0}", pBitRate);

            Process process = new Process();
            process.StartInfo = new ProcessStartInfo();
            process.StartInfo.FileName = lameEXE;
            process.StartInfo.Arguments = string.Format(
                "{0} {1} {2}",
                lameArgs,
                fixedWaveName,
                fixedOutName);

            process.Start();
            process.WaitForExit();

            int exitCode = process.ExitCode;

            // insert the ID3v2 tags
            FileStream fs = new FileStream(pOutputFileName, FileMode.Open);
            FrameManager.Serialize(create_ID3v2_Tags(pAuthor, pTitle, pCopyright, pMilliseconds), fs);

            return (exitCode == 0);

        }

        private FrameModel create_ID3v2_Tags(string pAuthor, string pTitle, string pCopyright, int pMilliseconds)
        {

            FrameModel tagModel = new FrameModel();
            FrameBase frameBase;

            frameBase = new FrameText("TPE1");
            tagModel.Frames.Add(frameBase);
            ((FrameText)frameBase).Text = pAuthor;

            frameBase = new FrameText("TIT2");
            tagModel.Frames.Add(frameBase);
            ((FrameText)frameBase).Text = pTitle;

            frameBase = new FrameText("TCOP");
            tagModel.Frames.Add(frameBase);
            ((FrameText)frameBase).Text = pCopyright;

            frameBase = new FrameText("TLEN");
            tagModel.Frames.Add(frameBase);
            ((FrameText)frameBase).Text = pMilliseconds.ToString();

            int tagSize;
            if (tagModel.Header.Footer == true)
            {
                tagSize = tagModel.Header.TagSize + 20;
            }
            else
            {
                tagSize = tagModel.Header.TagSize + 10;
            }

            return tagModel;

        }

        public static string Get_Lame_Version()
        {

            BE_VERSION ver = new BE_VERSION();
            Lame_encDll.beVersion(ver);

            string returnVal = "   LAME version:  ";
            returnVal += ver.byMajorVersion.ToString() + "." + ver.byMinorVersion.ToString() + "\r\n";
            returnVal += "   LAME dll version:  ";
            returnVal += ver.byDLLMajorVersion.ToString() + "." + ver.byDLLMinorVersion.ToString() + "\r\n";

            return returnVal;
        }

        private string AppPath
        {
            get
            {
                string path = System.Windows.Forms.Application.ExecutablePath;
                path = path.Substring(0, path.LastIndexOf(@"\") + 1);
                return path;
            }
        }
    }
}
